package com.zyf.kafka.producer;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author Malegod_xiaofei
 * @create 2024-08-20-21:08
 */
public class KafkaProducerCallbackTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 创建配置对象
        Map<String, Object> configMap = new HashMap<>();
        configMap.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        // 对生产的数据 k,v 进行序列化的操作
        configMap.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        configMap.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        configMap.put(ProducerConfig.ACKS_CONFIG, "0");

        // TODO 创建生产者对象
        //     生产者对象需要设置泛型：数据类型的约束
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(configMap);


        for (int i = 0; i < 10; i++) {
            ProducerRecord<String, String> record = new ProducerRecord<String, String>(
                    "test1", "key" + i, "value" + i
            );
            Future<RecordMetadata> send = kafkaProducer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata metadata, Exception exception) {
                    System.out.println("数据发送成功：" + metadata);
                }
            });
            System.out.println("发送数据");
            // TODO 同步发送
            send.get();
        }
        // TODO 关闭生产者对象
        kafkaProducer.close();

    }
}
